from src.database.connection import HospitalDatabase
import tkinter.messagebox

# Initialize database connection
db = HospitalDatabase()
if not db.connect():
    print("Failed to connect to database")
    exit()

class BillingBackend:
    """Backend logic for billing management"""
    
    def __init__(self):
        self.db = db
    
    def add_invoice(self, invoice_data):
        """Add a new invoice to the database"""
        try:
            return self.db.add_invoice(
                patient_id=invoice_data['patient_id'],
                appointment_id=invoice_data['appointment_id'],
                invoice_date=invoice_data['invoice_date'],
                due_date=invoice_data['due_date'],
                subtotal=invoice_data['subtotal'],
                tax_amount=invoice_data.get('tax_amount', 0),
                total_amount=invoice_data['total_amount'],
                status=invoice_data.get('status', 'pending')
            )
        except Exception as e:
            raise Exception(f"Error adding invoice: {str(e)}")
    
    def update_invoice(self, invoice_id, update_data):
        """Update invoice information"""
        try:
            return self.db.update_invoice(invoice_id, **update_data)
        except Exception as e:
            raise Exception(f"Error updating invoice: {str(e)}")
    
    def delete_invoice(self, invoice_id):
        """Delete an invoice from the database"""
        try:
            return self.db.delete_invoice(invoice_id)
        except Exception as e:
            raise Exception(f"Error deleting invoice: {str(e)}")
    
    def get_invoice(self, invoice_id):
        """Get invoice by ID"""
        try:
            return self.db.get_invoice(invoice_id)
        except Exception as e:
            raise Exception(f"Error getting invoice: {str(e)}")
    
    def get_all_invoices(self):
        """Get all invoices from database"""
        try:
            return self.db.get_all_invoices()
        except Exception as e:
            raise Exception(f"Error getting all invoices: {str(e)}")
    
    def validate_invoice_data(self, invoice_data):
        """Validate invoice data before saving"""
        required_fields = ['patient_id', 'appointment_id', 'invoice_date', 'due_date', 'subtotal', 'total_amount']
        
        for field in required_fields:
            if not invoice_data.get(field):
                return False, f"Field '{field}' is required"
        
        # Validate patient_id is positive
        try:
            patient_id = int(invoice_data['patient_id'])
            if patient_id <= 0:
                return False, "Patient ID must be a positive number"
        except ValueError:
            return False, "Patient ID must be a valid number"
        
        # Validate appointment_id is positive
        try:
            appointment_id = int(invoice_data['appointment_id'])
            if appointment_id <= 0:
                return False, "Appointment ID must be a positive number"
        except ValueError:
            return False, "Appointment ID must be a valid number"
        
        # Validate subtotal is positive
        try:
            subtotal = float(invoice_data['subtotal'])
            if subtotal <= 0:
                return False, "Subtotal must be a positive number"
        except ValueError:
            return False, "Subtotal must be a valid number"
        
        # Validate total_amount is positive
        try:
            total_amount = float(invoice_data['total_amount'])
            if total_amount <= 0:
                return False, "Total amount must be a positive number"
        except ValueError:
            return False, "Total amount must be a valid number"
        
        # Validate tax_amount if provided
        if invoice_data.get('tax_amount'):
            try:
                tax_amount = float(invoice_data['tax_amount'])
                if tax_amount < 0:
                    return False, "Tax amount cannot be negative"
            except ValueError:
                return False, "Tax amount must be a valid number"
        
        return True, "Valid"
    
    def calculate_tax(self, subtotal, tax_rate=0.1):
        """Calculate tax amount based on subtotal"""
        return subtotal * tax_rate
    
    def calculate_total(self, subtotal, tax_amount):
        """Calculate total amount"""
        return subtotal + tax_amount

